package com.shoes.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author asen
 */
public class HttpUtils {

    /**
     *
     * @param get 封装好的HttpGet
     * @return get请求返回数据,String类型
     */
    public static String get_send(HttpGet get) {
        String result;
        try {
            HttpClient client = HttpClients.createDefault();
            HttpResponse response = client.execute(get);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (IOException e) {
            e.printStackTrace();
            result = null;
        }
        return result;
    }

    /**
     *
     * @param post 封装好的HttpGet
     * @return post请求返回数据,String类型
     */
    public static String post_send(HttpPost post) {
        String result;
        try {
            HttpClient client = HttpClients.createDefault();
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
            result = null;
        }
        return result;
    }

    public static String get(String url) {
        HttpGet get = new HttpGet(url);
        String result = get_send(get);
        return result;
    }

    public static String post(String url) {
        HttpPost post = new HttpPost(url);
        String result = post_send(post);
        return result;
    }
}
